package com.qiusuo0226.core.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.qiusuo0226.common.constant.NumConstant;
import com.qiusuo0226.mvc.util.JsonResultModel;
import com.qiusuo0226.security.config.SecurityProperty;
import com.qiusuo0226.security.util.JWTTool;
import com.qiusuo0226.core.pojo.dto.UserInfoDTO;
import com.qiusuo0226.core.pojo.query.LoginBean;
import com.qiusuo0226.core.service.LoginService;
import com.qiusuo0226.core.service.UserInfoService;
import com.qiusuo0226.core.util.UserInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.Security;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qiusuo
 * @date 2023/6/19 11:57
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SecurityProperty property;

    @Override
    public JsonResultModel signIn(String remoteHost, LoginBean bean) {
        UserInfoDTO userInfoDTO = null;
        // type=1 账号密码登录，type=2 邮箱验证码登录，type=3 手机验证码登录
        if (StringUtils.equals(bean.getType(), NumConstant.S1)) {
            userInfoDTO = userInfoService.queryByAccountAndPass(bean.getAccount(), bean.getPwd());
            if (null == userInfoDTO) {
                return JsonResultModel.failure("30001", "账号或密码错误，登录失败");
            }
        }

        // 获取用户的权限信息
        JSONObject permission = new JSONObject();

        JSONArray corePermission = new JSONArray();
        corePermission.add("core:*");
        permission.put("core", corePermission);

        JSONArray defaultPagePermission = new JSONArray();
        defaultPagePermission.add("defaultPage:*");
        permission.put("defaultPage", defaultPagePermission);

        JSONArray selfPermission = new JSONArray();
        selfPermission.add("self:*");
        permission.put("self", selfPermission);

        // 组装用户基本信息
        JSONObject userInfoObj = new JSONObject();
        userInfoObj.put("name", userInfoDTO.getUserName());
        userInfoObj.put("iid", userInfoDTO.getIid());

        // 组织token生成必要参数
        Map<String, String> payload = new HashMap(NumConstant.N16);
        payload.put("ip", remoteHost);
        payload.put("iid", userInfoDTO.getIid());
        // 生成有效期为1天的token
        String token = JWTTool.getToken(payload, property.getJwtKey(), NumConstant.N1DAY);
        // token作为key把用户信息存入缓存，1天有效
        JSONObject cacheJson = new JSONObject();
        cacheJson.put("token", token);
        cacheJson.put("data", userInfoDTO);
        UserInfoUtil.setCache(userInfoDTO.getIid(), cacheJson, NumConstant.N1DAY);
        // 封装返回结果
        JSONObject result = new JSONObject();
        result.put("token", token);
        result.put("permission", permission);
        result.put("userInfo", userInfoObj);
        return JsonResultModel.success("登录成功", result);
    }

    @Override
    public JsonResultModel signOut(String token, long userId) {
        try {
            cn.hutool.json.JSONObject verify = JWTTool.verify(token, property.getJwtKey());
            Long tokenId = verify.getLong("iid");
            // 若tokenId和传过来的用户Id相等
            if (tokenId == userId) {
                UserInfoUtil.removeCache(String.valueOf(userId));
                return JsonResultModel.success("登出成功");
            }
        } catch (Exception e) {
            log.error("token校验异常", e);
            return JsonResultModel.tokenError();
        }
        return JsonResultModel.failure(NumConstant.S30001,"登出失败，待登出用户唯一标识和token生成的用户唯一标识不一致");
    }
}
